package com.mall.shopping.services;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.shopping.ICartListService;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/*要定义为一个服务才能被远程方法调用,只能是dubbo的service注解，如果使用Springfrimwork注解就不能远程调用了
* 把它作为一个服务的代理对象放到容器当中，等待服务被调用*/

@Service
public class ICartListServiceImpl implements ICartListService {

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public List<CartListShowTwoDTO> getCartListShow(CartListByIdRequest cartListByIdRequest) {
        //直接去把商品ID查出来就行了，使用定义好的mapper

        //首先，先拿到userid或者说username
        //这个Userinfo就是用户姓名  cartListShowRequest.getUserInfo()
        RMap<Integer, CartListShowDTO> map = redissonClient.getMap(cartListByIdRequest.getUserId().toString());
        ObjectMapper objectMapper = new ObjectMapper();
        ArrayList<CartListShowTwoDTO> cartListShowDTOS = new ArrayList<>();
        for (Map.Entry<Integer, CartListShowDTO> entry : map.entrySet()) {
            //System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
            //需要把json转成对象
            //CartListShowDTO cartListShowDTO1 = objectMapper.readValue()
            //CartListShowDTO cartListShowDTO = new CartListShowDTO(entry.getKey(),entry.getValue().getSalePrice(),entry.getValue().getProductNum(),entry.getValue().getLimitNum(),entry.getValue().getChecked(),entry.getValue().getProductName(),entry.getValue().getProductImg());
            String strBoolean = String.valueOf(entry.getValue().getChecked());
            CartListShowTwoDTO cartListShowTwoDTO = new CartListShowTwoDTO(entry.getKey(),entry.getValue().getSalePrice(),entry.getValue().getProductNum(),entry.getValue().getLimitNum(),strBoolean,entry.getValue().getProductName(),entry.getValue().getProductImg().split(",")[0]);
            //entry.getValue().getChecked()是个boolean类型
            //if (!equals(entry.getValue().getChecked())){
            cartListShowDTOS.add(cartListShowTwoDTO);
          // }
        }

        return cartListShowDTOS;
    }
}
